{% extends "base.html" %}

{% block content %}
<div class="min-h-screen gradient-bg">
    <!-- Header -->
    <div class="container mx-auto px-4 py-12">
        <div class="text-center mb-12">
            <h1 class="text-5xl font-bold text-white mb-4">
                <i class="fas fa-code mr-3"></i>
                代码开发规范生成工具
            </h1>
            <p class="text-xl text-white opacity-90">基于AI的智能开发规范生成平台</p>
        </div>

        <!-- Main Content -->
        <div class="max-w-4xl mx-auto">
            <!-- Input Section -->
            <div id="input-section" class="bg-white rounded-2xl shadow-xl p-8 mb-8 card-hover">
                <h2 class="text-2xl font-semibold text-gray-800 mb-6">
                    <i class="fas fa-edit mr-2 text-blue-500"></i>
                    项目描述
                </h2>
                
                <form id="project-form" onsubmit="generateDocuments(event)">
                    <div class="mb-6">
                        <label for="project_description" class="block text-sm font-medium text-gray-700 mb-2">
                            请详细描述您的项目需求：
                        </label>
                        <textarea 
                            id="project_description" 
                            name="project_description" 
                            rows="8"
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
                            placeholder="例如：开发一个电商网站，需要用户注册登录、商品浏览、购物车、订单管理等功能。使用Python Flask后端，React前端，MySQL数据库..."
                            required
                        ></textarea>
                    </div>
                    
                    <div class="flex justify-center">
                        <button 
                            type="submit" 
                            id="submit-btn"
                            class="bg-gradient-to-r from-blue-500 to-purple-600 text-white px-8 py-3 rounded-lg font-semibold hover:from-blue-600 hover:to-purple-700 transition-all duration-200 transform hover:scale-105"
                        >
                            <i class="fas fa-magic mr-2"></i>
                            生成开发规范
                        </button>
                    </div>
                </form>
            </div>

            <!-- Loading Section -->
            <div id="loading" class="hidden bg-white rounded-2xl shadow-xl p-8 mb-8">
                <div class="text-center mb-6">
                    <h3 class="text-xl font-semibold text-gray-800 mb-2">正在生成文档...</h3>
                    <p class="text-gray-600">AI正在为您生成专业的开发规范文档</p>
                </div>
                
                <!-- 进度条 -->
                <div class="mb-6">
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm font-medium text-gray-700" id="step-name">准备中...</span>
                        <span class="text-sm font-medium text-blue-600" id="progress-percent">0%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-3">
                        <div id="progress-bar" class="bg-gradient-to-r from-blue-500 to-purple-600 h-3 rounded-full transition-all duration-500 ease-out" style="width: 0%"></div>
                    </div>
                </div>
                
                <!-- 调试信息 -->
                <div class="bg-gray-50 rounded-lg p-4 max-h-40 overflow-y-auto">
                    <h4 class="text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-terminal mr-1 text-green-500"></i>
                        调试信息
                    </h4>
                    <div id="debug-info" class="text-xs text-gray-600 font-mono space-y-1">
                        <div>等待开始...</div>
                    </div>
                </div>
            </div>

            <!-- Results Section -->
            <div id="results-section" class="hidden bg-white rounded-2xl shadow-xl p-8">
                <h2 class="text-2xl font-semibold text-gray-800 mb-6">
                    <i class="fas fa-file-alt mr-2 text-green-500"></i>
                    生成的文档
                </h2>
                
                <div class="grid md:grid-cols-3 gap-6">
                    <!-- Global Role Card -->
                    <div class="bg-blue-50 rounded-xl p-6 card-hover">
                        <div class="text-center">
                            <i class="fas fa-globe text-3xl text-blue-500 mb-3"></i>
                            <h3 class="text-lg font-semibold text-gray-800 mb-2">全局规范</h3>
                            <p class="text-sm text-gray-600 mb-4">项目整体开发规范</p>
                            <button 
                                onclick="downloadFile('global_role')"
                                class="bg-blue-500 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-600 transition-colors"
                            >
                                <i class="fas fa-download mr-1"></i>
                                下载
                            </button>
                        </div>
                    </div>

                    <!-- Project Plan Card -->
                    <div class="bg-green-50 rounded-xl p-6 card-hover">
                        <div class="text-center">
                            <i class="fas fa-project-diagram text-3xl text-green-500 mb-3"></i>
                            <h3 class="text-lg font-semibold text-gray-800 mb-2">项目计划</h3>
                            <p class="text-sm text-gray-600 mb-4">详细的项目规划</p>
                            <button 
                                onclick="downloadFile('project_plan')"
                                class="bg-green-500 text-white px-4 py-2 rounded-lg text-sm hover:bg-green-600 transition-colors"
                            >
                                <i class="fas fa-download mr-1"></i>
                                下载
                            </button>
                        </div>
                    </div>

                    <!-- Detail Task Card -->
                    <div class="bg-purple-50 rounded-xl p-6 card-hover">
                        <div class="text-center">
                            <i class="fas fa-tasks text-3xl text-purple-500 mb-3"></i>
                            <h3 class="text-lg font-semibold text-gray-800 mb-2">详细任务</h3>
                            <p class="text-sm text-gray-600 mb-4">任务分解和规划</p>
                            <button 
                                onclick="downloadFile('detail_task')"
                                class="bg-purple-500 text-white px-4 py-2 rounded-lg text-sm hover:bg-purple-600 transition-colors"
                            >
                                <i class="fas fa-download mr-1"></i>
                                下载
                            </button>
                        </div>
                    </div>
                </div>

                <div class="text-center mt-8">
                    <button 
                        onclick="resetForm()"
                        class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition-colors"
                    >
                        <i class="fas fa-redo mr-2"></i>
                        重新生成
                    </button>
                </div>
            </div>

            <!-- Error Message -->
            <div id="error-message" class="hidden bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>
                    <span class="text-red-700 font-medium" id="error-text"></span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let currentFiles = {};
    let progressInterval = null;

    async function generateDocuments(event) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const projectDescription = formData.get('project_description');
        
        if (!projectDescription.trim()) {
            showError('请输入项目描述');
            return;
        }
        
        showLoading();
        startProgressPolling();
        
        try {
            const response = await fetch('/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(formData)
            });
            
            const result = await response.json();
            
            if (response.ok) {
                currentFiles = result;
                document.getElementById('input-section').classList.add('hidden');
                document.getElementById('results-section').classList.remove('hidden');
            } else {
                showError(result.error || '生成文档时出错');
            }
        } catch (error) {
            showError('网络错误，请重试');
        } finally {
            stopProgressPolling();
            hideLoading();
        }
    }
    
    function startProgressPolling() {
        progressInterval = setInterval(async () => {
            try {
                const response = await fetch('/progress');
                const progress = await response.json();
                
                // 更新进度条
                document.getElementById('progress-bar').style.width = `${progress.progress_percent}%`;
                document.getElementById('progress-percent').textContent = `${progress.progress_percent}%`;
                document.getElementById('step-name').textContent = progress.step_name || '处理中...';
                
                // 更新调试信息
                const debugInfoElement = document.getElementById('debug-info');
                debugInfoElement.innerHTML = '';
                
                if (progress.debug_info && progress.debug_info.length > 0) {
                    progress.debug_info.forEach(info => {
                        const div = document.createElement('div');
                        div.textContent = info;
                        div.className = 'text-xs text-gray-600 font-mono';
                        debugInfoElement.appendChild(div);
                    });
                } else {
                    const div = document.createElement('div');
                    div.textContent = '等待开始...';
                    div.className = 'text-xs text-gray-600 font-mono';
                    debugInfoElement.appendChild(div);
                }
                
                // 自动滚动到底部
                debugInfoElement.scrollTop = debugInfoElement.scrollHeight;
                
            } catch (error) {
                console.error('获取进度信息失败:', error);
            }
        }, 500); // 每500毫秒更新一次
    }
    
    function stopProgressPolling() {
        if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
        }
    }
    
    function downloadFile(fileType) {
        const filename = currentFiles[fileType];
        if (filename) {
            window.open(`/download/${filename}`, '_blank');
        } else {
            showError('文件未生成，请重新提交');
        }
    }
    
    function resetForm() {
        document.getElementById('project-form').reset();
        document.getElementById('results-section').classList.add('hidden');
        document.getElementById('input-section').classList.remove('hidden');
        currentFiles = {};
        
        // 重置进度条状态
        document.getElementById('progress-bar').style.width = '0%';
        document.getElementById('progress-percent').textContent = '0%';
        document.getElementById('step-name').textContent = '准备中...';
        document.getElementById('debug-info').innerHTML = '<div>等待开始...</div>';
    }
</script>
{% endblock %}